import { Alert, Col, Form, Input, Row } from 'antd';
import { useTranslation } from 'react-i18next';

import {
  REG_CHINESE,
  REG_COLOR,
  REG_DATE,
  REG_EMAIL,
  REG_IDCODE,
  REG_IPV4,
  REG_PHONE,
  REG_POSTCODE,
} from '@/utils/commonReg';

interface OptionalFormItem {
  name: string;
  label: string;
  defaultValue: string;
  reg: RegExp;
}

const InputValidation = () => {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const items: OptionalFormItem[] = [
    {
      name: 'id',
      label: t('ID'),
      defaultValue: '',
      reg: REG_IDCODE,
    },
    {
      name: 'email',
      label: t('email'),
      defaultValue: '',
      reg: REG_EMAIL,
    },
    {
      name: 'phone',
      label: t('phone'),
      defaultValue: '',
      reg: REG_PHONE,
    },
    {
      name: 'chinese',
      label: t('chinese'),
      defaultValue: '中文',
      reg: REG_CHINESE,
    },
    {
      name: 'ip',
      label: 'IPV4',
      defaultValue: '192.168.1.1',
      reg: REG_IPV4,
    },
    {
      name: 'postcode',
      label: t('postcode'),
      defaultValue: '350300',
      reg: REG_POSTCODE,
    },
    {
      name: 'color',
      label: t('color'),
      defaultValue: '#ffffff',
      reg: REG_COLOR,
    },
    {
      name: 'date',
      label: t('date'),
      defaultValue: '2023-02-11',
      reg: REG_DATE,
    },
  ];

  return (
    <>
      <Alert showIcon className="mb-4" type="warning" message={t('inputValidationAdvice')} />
      <Form labelAlign="right" form={form}>
        <Row gutter={{ xs: 30, sm: 30, md: 30, lg: 30, xl: 30, xxl: 30 }}>
          {items.map(({ name, label, reg, defaultValue }, idx) => (
            <Col xs={24} sm={24} md={24} lg={12} xl={12} xxl={12} key={idx}>
              <Form.Item
                name={name}
                label={label}
                rules={[
                  {
                    validator: (_, val) => (reg.test(val) ? Promise.resolve() : Promise.reject()),
                    message: '格式错误',
                  },
                ]}
              >
                <Input defaultValue={defaultValue} />
              </Form.Item>
            </Col>
          ))}
        </Row>
      </Form>
    </>
  );
};

export default InputValidation;
